<template>
  <div class='container'>
    <el-card>
      <div slot="header" class="clearfix">
        {{$route.query.id ? "试题修改" : "试题录入"}}
      </div>
      <el-form label-width="100px" :model="newQForm" :rules="rules" ref="formRef" >
        <el-form-item label="学科：" prop="subjectID">
          <el-select v-model="newQForm.subjectID" style="width:30%" @change="getCatalogList">
            <el-option v-for="item in subjectList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录：" prop="catalogID">
          <el-select v-model="newQForm.catalogID" style="width:30%">
            <el-option v-for="item in catalogList" :key="item.id" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业：" prop="enterpriseID">
          <el-select v-model="newQForm.enterpriseID" style="width:30%">
            <el-option v-for="item in companyList" :key="item.id" :label="item.company" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市：" prop="city">
          <!-- <el-col :span="12"> -->
            <el-select v-model="newQForm.province" placeholder="请选择" style="width:15%" @change="getAreaOptions">
              <el-option
                v-for="item in cityList"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          <!-- </el-col>
          <el-col :span="12"> -->
            <el-select v-model="newQForm.city" placeholder="请选择" style="width:15%">
              <el-option
                v-for="item in areaList"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          <!-- </el-col> -->
        </el-form-item>
        <el-form-item label="方向：" prop="direction">
          <el-select v-model="newQForm.direction" style="width:30%">
            <el-option v-for="item in directionOptions" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型：" prop="questionType">
          <!-- 此处调用是为了在切换下方单选\多选显示时，重置选项为不选中状态，否则会出现问题 -->
          <el-radio-group v-model="newQForm.questionType" @change="changeState({})">
            <el-radio v-for="item in questionTypeOptions" :key="item.value" :label="item.value+''">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度：" prop="difficulty">
          <el-radio-group v-model="newQForm.difficulty">
            <el-radio v-for="item in difficultyOptions" :key="item.value" :label="item.value+''" >{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干：" prop="question">
          <quill-editor :options="editorOption" v-model="newQForm.question"></quill-editor>
        </el-form-item>
        <!-- 题型选择为单选时显示单选框 -->
        <!-- 题型选择为多选时显示多选框 -->
        <el-form-item label="选项：" prop="options" v-if="newQForm.questionType !== '3'">
          <div class="selectBox" v-for="item in newQForm.options" :key="item.code">
            <el-radio v-if="newQForm.questionType === '1'" v-model="item.isRight" @change="changeState(item)" :label="true">{{item.code}}</el-radio>
            <el-checkbox v-if="newQForm.questionType === '2'" v-model="item.isRight" :label="true">{{item.code}}</el-checkbox>
            <el-input style="width:20%" v-model="item.title"></el-input>
            <el-upload
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false">
                <img v-if="item.img" :src="item.img" class="avatar">
                <i v-else class="el-icon-circle-close avatar-uploader-icon"></i>
                上传图片
              </el-upload>
          </div>
          <!-- 添加按钮 -->
          <el-button type="danger" :disabled="newQForm.questionType!=='2'" @click="addOption" size="small">+增加选项与答案</el-button>
        </el-form-item>
        <el-form-item label="解析视频：" prop="videoURL">
          <el-input v-model="newQForm.videoURL" style="width:30%"></el-input>
        </el-form-item>
        <el-form-item label="答案解析：" prop="answer">
          <quill-editor v-model="newQForm.answer" :options="editorOption"></quill-editor>
        </el-form-item>
        <el-form-item label="题目备注：" prop="remarks">
          <el-input v-model="newQForm.remarks" type="textarea" style="width:30%"></el-input>
        </el-form-item>
        <el-form-item label="试题标签：" prop="tags">
          <el-select style="width:30%" v-model="newQForm.tags" multiple placeholder="请选择">
            <el-option
              v-for="item in simpleTagsList"
              :key="item.value"
              :label="item.label"
              :value="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button v-if="!$route.query.id" type="primary" @click="submitQuestion">确认提交</el-button>
          <el-button v-else type="success" @click="updateQuestion">确认修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { add, detail, update } from '@/api/hmmm/questions.js'
import { simple as reqSimpleTagsList } from '@/api/hmmm/tags.js'
import { simple } from '@/api/hmmm/subjects.js'
import { simple as reqGetCatalogList } from '@/api/hmmm/directorys.js'
import { list as reqGetCompanyList } from '@/api/hmmm/companys.js'
import { provinces, citys as areaOptions } from '@/api/hmmm/citys.js'
import { direction as directionOptions, difficulty as difficultyOptions, questionType as questionTypeOptions } from '@/api/hmmm/constants.js'
export default {
  name: 'NewQ',
  data () {
    return {
      newQForm: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '1',
        difficulty: '',
        question: '',
        options: [
          { code: 'A：', title: '', img: '', isRight: false },
          { code: 'B：', title: '', img: '', isRight: false },
          { code: 'C：', title: '', img: '', isRight: false },
          { code: 'D：', title: '', img: '', isRight: false }
        ],
        videoURL: '',
        answer: '',
        remarks: '',
        tags: []
      },
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ]
      },
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            ['blockquote', 'code-block'], // 引用  代码块
            ['link', 'image'] // 链接、图片
          ] // 工具菜单栏配置
        },
        placeholder: '请在这里添加产品描述', // 提示
        readyOnly: false, // 是否只读
        theme: 'snow', // 主题 snow/bubble
        syntax: true // 语法检测
      },
      num: 1,
      subjectList: [],
      catalogList: [],
      cityList: provinces(),
      areaList: [],
      directionOptions,
      difficultyOptions,
      questionTypeOptions,
      companyList: [],
      simpleTagsList: []
    }
  },
  created () {
    this.getSubjectList()
    this.getCompanyList()
    this.getSimpleTagsList()
    // console.log(provinces())
    // console.log(this.$route)
    if (this.$route.query.id) {
      this.getQuestion()
    }
    console.log(this.$route)
  },
  methods: {
    // 根据id获取题库详情
    async getQuestion () {
      const { data } = await detail({ id: this.$route.query.id })
      // console.log(data)
      data.tags = data.tags.split(',')
      data.options.forEach(item => { item.isRight = item.isRight === 1 })
      // console.log(data.options)
      this.newQForm = data
      // 根据现有的学科id重新获取目录列表
      const res = await reqGetCatalogList({ subjectID: this.newQForm.subjectID })
      // console.log(res)
      this.catalogList = res.data
    },
    // 获取学科列表
    async getSubjectList () {
      const { data } = await simple()
      console.log(data)
      this.subjectList = data
    },
    // 获取目录列表
    async getCatalogList () {
      this.newQForm.catalogID = ''
      const { data } = await reqGetCatalogList({ subjectID: this.newQForm.subjectID })
      console.log(data)
      this.catalogList = data
    },
    // 获取企业列表
    async getCompanyList () {
      const { data: { items } } = await reqGetCompanyList({ pagesize: 99999 })
      console.log(items)
      this.companyList = items
    },
    // 根据城市获取区域列表
    getAreaOptions () {
      this.areaList = areaOptions(this.newQForm.province)
    },
    // 获取简单标签列表
    async getSimpleTagsList () {
      const { data } = await reqSimpleTagsList({ pagesize: 9999 })
      console.log(data)
      this.simpleTagsList = data
    },
    // 单选框
    changeState (option) {
      this.newQForm.options.forEach(item => { item.isRight = false })
      option.isRight = true
    },
    // 添加选项
    addOption () {
      // 规律：
      // 索引 0 ---> A  ascii  65
      // 索引 1 ---> B  ascii  66
      // 索引 2 ---> C  ascii  67
      // 索引 3 ---> D  ascii  68
      // 索引 4 ---> E  ascii  69
      // ...
      // 总结 code = String.fromCharCode(index + 65)
      this.newQForm.options.push({
        isRight: false,
        code: String.fromCharCode(65 + this.newQForm.options.length) + '：',
        title: '',
        img: ''
      })
    },
    // 提交试题
    submitQuestion () {
      this.$refs.formRef.validate(async boo => {
        if (boo) {
          this.newQForm.tags = this.newQForm.tags.join(',')
          await add(this.newQForm)
          // console.log(res)
          // this.$refs.formRef.resetFields()
          this.$message.success('添加成功')
          this.$router.push('/questions/list')
        }
      })
    },
    // 修改试题提交
    updateQuestion () {
      this.$refs.formRef.validate(async boo => {
        if (boo) {
          this.newQForm.tags = this.newQForm.tags.join(',')
          await update(this.newQForm)
          this.$message.success('修改成功')
          this.$router.push('/questions/list')
        }
      })
    }
  }
}
</script>

<style scoped lang='scss'>
::v-deep .ql-editor{
  height: 200px;
}
::v-deep .avatar-uploader{
  display: inline-block;
  vertical-align: middle;
  width: 80px;
  height: 50px;
  border: 1px dashed #ccc;
  border-radius: 5px;
  margin-left: 5px;
  position: relative;
  text-align: center;
  line-height: 50px;
}
.selectBox{
  margin: 5px 0;
}
::v-deep .avatar-uploader-icon{
  position: absolute;
  top: -5px;
  right: -5px;
}
</style>
